'''
Description: 文字接收器模块
Author: HowsenFisher
Date: 2021-04-01 21:48:08
LastEditTime: 2021-04-11 01:21:34
LastEditors: liutq
Reference: 
'''
import socket
from PyQt5.QtWidgets import *
from threading import Thread
from sql.DB import *
import time
from Config import conf


class WordReceiver:

    '''
    @description: 文字接收器类
    @param  {*}
    @return {*}
    @param {*} self
    @param {*} parent：父对象
    @param {*} addr：本机地址
    @param {*} port：文字接收端口
    '''
    def __init__(self,parent,addr,port):
        # 父对象
        self.parent = parent
        # 创建TCP socket
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 本机IP地址
        self.addr = addr
        # 文字接收端口
        self.port = port
        # 绑定本机文字接收端口
        self.s.bind((addr,port))
        # 等待队列最长255
        self.s.listen(255)
        while True:
            # 接受对方的连接，获取到对方socket对象和地址
            client,clientAddr = self.s.accept()
            print(clientAddr)
            # 创建接收文字线程
            newReceiveThread = Thread(target=lambda:self.receiveWord(client,self.parent,clientAddr))
            # 开启线程
            newReceiveThread.start()
            
    '''
    @description: 接受文字函数
    @param  {*}
    @return {*}
    @param {*} self
    @param {*} client：对方的socket对象
    @param {*} parent：父对象
    @param {*} clientAddr：对方的地址
    '''
    def receiveWord(self,client,parent,clientAddr):
        while True:
            # 尝试接收消息，若接到空串就停止
            # （在编写这段代码时发现对方断开连接本机会收到空串，这是一种妥协）
            data=b""
            try:
                data = client.recv(1024)
                print(data.decode('utf-8'))
                if data==b'':
                    break
            # 若对方断开连接，recv会发生错误，关闭这个连接
            except Exception:
                client.close()
                print("由于断开，关闭了一个文字接收线程")
                break
            # 向数据库插入消息
            insertMessage(Sender=clientAddr[0],Receiver=conf.ip,time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())),content=data.decode("utf-8"))
            # 聊天框新增消息
            parent.newMessageSignal.emit(data.decode('utf-8'))


if __name__ == '__main__':
    myWordReceiver = WordReceiver("192.168.0.4",913)
    myWordReceiver.receiveWord()